package com.wanrue.tcc.filter;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.*;
import com.wanrue.tcc.annotation.Tcc;
import com.wanrue.tcc.common.ContextService;
import com.wanrue.tcc.common.TccMethod;
import com.wanrue.tcc.core.TransactionInterceptor;
import lombok.Setter;

import java.lang.reflect.Method;

@Setter
@Activate(group = {Constants.CONSUMER})
public class TransactionFilter implements Filter {

    private ContextService contextService;

    private TransactionInterceptor tccTransactionInterceptor;

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        try {
            Class<?> target = invoker.getInterface();
            Method method = target.getMethod(invocation.getMethodName(), invocation.getParameterTypes());
            Tcc annotation = method.getAnnotation(Tcc.class);
            if (annotation != null) {
                TccMethod tccMethod = contextService.method(null, invoker, invocation);
                tccTransactionInterceptor.normalProceed(tccMethod);
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return invoker.invoke(invocation);
    }
}
